# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 单一聚合avg操作.py
# @Author: dongguangwen
# @Date  : 2025-06-14 18:52
from pymongo import MongoClient

# 连接到MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']


pipeline = [
    {
        "$group": {
            "_id": None,
            "average_age": {"$avg": "$age"}
        }
    }
]

result = list(db.users.aggregate(pipeline))
print(result)
print("平均年龄:", round(result[0]["average_age"], 2))

result2 = collection.aggregate(pipeline)
print(result2)
print(list(result2))

"""
[{'_id': None, 'average_age': 35.5}]
平均年龄: 35.5
<pymongo.synchronous.command_cursor.CommandCursor object at 0x000002211D413290>
[{'_id': None, 'average_age': 35.5}]
"""